<template>
  <div class="map-container" id="mapview"></div>
  <div class="max-layer-index">{{ layerMaxIndex }}</div>
  <!-- <SvgIcon iconClass="bug" className="bugclass" /> -->
</template>

<!--  <script lang="ts"> -->
<script>
import { defineComponent, onMounted, createApp, ref } from "vue";
// import 
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
// import FeatureLayer from '@arcgis/core/layers/FeatureLayer';
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Graphic from "@arcgis/core/Graphic";
import WMSLayer from "@arcgis/core/layers/WMSLayer";
import LayerList from "@arcgis/core/widgets/LayerList";
import ScaleBar from "@arcgis/core/widgets/ScaleBar";
import gisConfig from "../config/gisConfig.js";
import axios from "axios";
import testIcon from "@/assets/test-icon.svg";
import PopupContent from '@/views/PopupContent.vue';
// import SvgIcon from '@/components/SvgIcon/index.vue'

const { basemap_url, tk, guangxiBoundry } = gisConfig

export default defineComponent({
  name: "MapContainer",
  components: {
    // SvgIcon,
  },
  setup() {
    onMounted(() => {
      handleCreateMap();
    });
		
    let map, view;
    let layerMaxIndex = ref(0);

    async function handleCreateMap() {
      const tiledLayer = new WebTileLayer({
        urlTemplate: basemap_url.image_url + tk,
        subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
        copyright: "天地图影像",
      });

      const tiledLayer_poi = new WebTileLayer({
        urlTemplate: basemap_url.sign_url + tk,
        subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
        copyright: "天地图影像标记",
      });

      map = new Map({
        basemap: {
          baseLayers: [tiledLayer, tiledLayer_poi],
        },
        layers: [],
      });

      view = new MapView({
        container: "mapview",
        map: map,
        zoom: 7,
        // scale: 2400000,
        center: [108.79199270119518, 23.908923693492856],
      });
      
      

      // 添加边界
      await addBoundryLayer();

      // 添加测站点 GraphicsLayer => Graphic(geometry:几何图形；symbol:符号；)
      await addStationPoint();
      
      // popup上的事件触发
      view.popup.on("trigger-action", function (event) {
        console.log(event);
        function adjustMapZoom(e, dir) {
          e.action.active = !e.action.active;
          view
            .goTo({
              center: view.center,
              zoom: view.zoom + dir * 2,
            })
            .then(() => {
              e.action.active = !e.action.active;
            });
        }
        switch (event.action.id) {
          case "zoom-out":
            adjustMapZoom(event, -1);
            break;
          case "zoom-in":
            adjustMapZoom(event, 1);
            break;
          case "show-hide":
            // view.popup.collapsed = event.action.value ? false : true;
            // view.popup.collapsed = true;
            console.log(event.action.value);
            event.action.title = event.action.value ? "隐藏内容" : "显示内容";
            break;
          default:
            break;
        }
      });
      
      // view.popup.collapsed = true;
      
      // dockOptions - 弹出框停靠相关设置
      view.popup.dockOptions = {
        buttonEnabled: false,
      };
      
      // collapseEnabled - 内容是否可以折叠
      view.popup.collapseEnabled = false;
      
      // 监听鼠标在view上移动事件
      view.on("pointer-move", (event) => {
        view.container.style.cursor = "default";
        view.hitTest(event).then((response) => {
          if (response.results.length) {
            // console.log(response);
            view.container.style.cursor = "pointer";
          }
        });
      });
      
      // 监听鼠标在view上的点击事件
      view.on("click", (event) => {
        console.log(event.mapPoint.longitude, event.mapPoint.latitude);
      });
      
      // 监听鼠标滚轮事件
      view.on("mouse-wheel", event => {
        // console.log(view.scale);

      });

      // 右上角加LayerList
      const layerList = new LayerList({
        view: view,
      });
      view.ui.add(layerList, "top-right");

      // 比例尺
      const scaleBar = new ScaleBar({
        view: view,
        style: 'ruler',
        unit: 'metric',
        declaredClass: 'cus-gis-scalebar',
      });
      view.ui.add(scaleBar, {
        position: "bottom-right"
      });

      // view.when()
      view.when(() => {
        
      });
    }

    /**
     * 添加边界图层
     * 1、边界添加完毕之后，再添加测站
     */
    function addBoundryLayer() {
      return new Promise((resolve, reject) => {
        guangxiBoundry.forEach((item, index) => {
          const subLayers = [];
          item.children.forEach(ele => {
            const sublayer = {
                id: ele.layerId,
                title: ele.title,
                name: ele.layerUrl,
                visible: ele.checked,
            };
            subLayers.push(sublayer);
          });
          // const starttime = new Date().getTime();
          // console.log("加边界-开始请求");
          const boundryLayer = new WMSLayer({
            id: item.key,
            title: item.title,
            url: item.layerUrl,
            sublayers: subLayers
          });
          // const endtime1 = new Date().getTime();
          // console.log("加边界-结束请求", endtime1 - starttime);
          map.add(boundryLayer, ++layerMaxIndex.value);
          // const endtime2 = new Date().getTime();
          // console.log("加边界-结束", endtime2 - endtime1);
        });
        resolve();
      });
    }

    // 添加测站，以及对应信息弹框
    function addStationPoint() {
      return new Promise(async (resolve, reject) => {
          const graphicsLayer=new GraphicsLayer({
            id: "test-stations-point",
            title: "测站图层",
            opacity: 1,
          });
          map.add(graphicsLayer, ++layerMaxIndex.value);

          const { data: stations }=await getStations();
          // console.log("加测站-开始");
          stations.forEach(station => {
            const symbol={
              type: "picture-marker",
              url: testIcon,
              width: "30px",
              height: "30px",
            };
            const point={
              type: "point",
              longitude: station.coord.lon,
              latitude: station.coord.lat,
              // spatialReference: 'WGS84',
            };
            const actions=[
              // {
              //   type: 'toggle',
              //   title: '显示内容',
              //   id: 'show-hide',
              //   value: false,
              //   visible: true,
              // },{
              //   type: 'button',
              //   title: '缩小',
              //   id: 'zoom-out',
              //   className: 'esri-icon-zoom-out-magnifying-glass', //给action的图标设置类名（内置图标类名）
              //   // image: testIcon,  //给action的图标设置图片，是个路径，优先级高于className属性
              //   // className: 'cus-esri-zoom-out-magnifying-glass',  //自定义类名
              //   active: false, //是否显示旋转器
              // },{
              //   type: 'button',
              //   title: '放大',
              //   id: 'zoom-in',
              //   className: 'esri-icon-zoom-in-magnifying-glass', //给action的图标设置类名（内置图标类名）
              //   // image: testIcon,  //给action的图标设置图片，是个路径，优先级高于className属性
              //   // className: 'cus-esri-zoom-out-magnifying-glass',  //自定义类名
              //   active: false, //是否显示旋转器
              // }
            ];
            const popupTemplate={
              title: "测站详细信息{ZIP}",
              // action属性：一些ActionButton或ActionToggle对象的数组
              actions,
              overwriteActions: true,


              // content: popContent,
              // content: '<img src="'+station.files[0].path+'">'
              content: [{
                type: 'custom',
                outFields: ["*"],
                creator: () => {
                  const contentDom = document.createElement('div');
                  contentDom.className='popup-container';
                  const oContent = createApp(PopupContent);
                  // console.log(oContent);
                  oContent.mount(contentDom);
                  return contentDom;
                }
              }]
            };
            const graphic=new Graphic({
              geometry: point,
              symbol: symbol,
              attributes: station,
              expressionInfo: {
                ZIP: '啦啦啦啦'
              },
              popupTemplate,
            });
            graphicsLayer.add(graphic);
          });
          // console.log("加测站-结束");
          resolve();
        })
      
    }
    // 请求测站数据
    function getStations() {
      return axios.get("./data/testStation.json");
    }

    return {
      layerMaxIndex,
    };
  },
});
</script>

<style lang="scss" scoped>
.map-container {
  height: 100%;

  .pop-content {
    text-align: center;

    .cus-station-title {
      font-size: 15px;
    }
    .status-online,
    .status-offline {
      font-size: 13px;
      font-weight: bold;
    }
    .status-online {
      color: rgb(0, 168, 50);
    }
    .status-offline {
      color: darkgray;
    }
  }
}

.max-layer-index {
  position: absolute;
  width: 100px;
  height: 100px;
  background: rgba(0, 78, 167, 0.705);
  top: 50%;
  left: 15px;
  transform: translateY(-50%);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
  color: #fff;
  display: none;
}
</style>